/* gulp */
var gulp = require("gulp");

/* 插件 */
var sass = require("gulp-sass"), //编译Sass
    autoprefixer = require("gulp-autoprefixer"), //自动添加css前缀
	cleanCSS = require('gulp-clean-css'); //css压缩
	uglify = require("gulp-uglify"), //js压缩
	imagemin = require("gulp-imagemin"), //JPG、PNG、GIF格式图片压缩
	jade = require('gulp-jade'), //jade模板编译
	runSequence = require("run-sequence"), //规定task执行顺序
	concat = require("gulp-concat"), //文件合并
	rename = require("gulp-rename"), //文件重命名
	clean = require("gulp-clean"), //删除文件和目录
	changed = require("gulp-changed"), //过滤未发生变化的文件
	spriter = require('gulp-css-spritesmith'),
	rev = require("gulp-rev"), //自动生成版本号
	revCollector = require("gulp-rev-collector"), //更新版本号
	sourcemaps = require("gulp-sourcemaps"),
	gulpIf = require("gulp-if"),
	plumber = require("gulp-plumber"),
	gulpUtil = require("gulp-util"),
	gulpData = require("gulp-data"),
	gulpPath = require("path"),
	gulpAdd = require("gulp-add"),
	mkdirp = require("mkdirp"),
	browserSync = require("browser-sync").create(), //实时刷新
	reload = browserSync.reload;

/* 配置 */
var project = "life", //项目名
	sourcemap = false, //是否开启sourcemap
	version = false, //是否开启版本控制
	build = false, //是否发布生产
	timestamp = +new Date(),
	path = {
		view: project + "/view/**/*.html",
		css: project + "/resources/css/**/*.css",
		js: project + "/resources/js/**/*.js",
		sass: project + "/resources/sass/**/*.scss",
		img: project + "/resources/img/**/*",
		jade: project + "/resources/tpl/jade/**/*.jade",
		catalog: { //项目目录结构
			view: project + "/view/",
			css: project + "/resources/css/",
			data: project + "/resources/data/",
			dep: project + "/resources/dep/",
			font: project + "/resources/font/",
			img: project + "/resources/img/",
			js: project + "/resources/js/",
			sass: project + "/resources/sass/",
			tpl: project + "/resources/tpl/"
		},
		src: { //开发目录
			view: project + "/view/",
			css: project + "/resources/css/",
			js: project + "/resources/js/",
			jadeView: project + "/view/tpl/jade/",
			jadeJs: project + "/resources/js/tpl/jade/",
			data: project + "/resources/data/",
			font: project + "/resources/font/",
			dep: project + "/resources/dep/**/*",
			ver: project + "/resources/data/ver/",
			cssVer: project + "/resources/data/ver/css/",
			jsVer: project + "/resources/data/ver/js/",
			imgVer: project + "/resources/data/ver/img/",
			sourcemap: project + "/resources/sourcemap/"
		},
		dist: { //压缩文件
			all: project + "/dist/",
			view: project + "/dist/view/",
			css: project + "/dist/resources/css/",
			js: project + "/dist/resources/js/",
			jadeJs: project + "/dist/resources/js/tpl/jade/",
			img: project + "/dist/resources/img/",
			font: project + "/dist/resources/font/",
			data: project + "/dist/resources/data/",
			dep: project + "/dist/resources/dep/"
		}
	};

/* css操作 */
/* 编译sass */
gulp.task("compile-sass", function() {
	return gulp.src(path.sass)
		.pipe(plumber())
		.pipe(gulpIf(sourcemap, sourcemaps.init()))
		.pipe(sass().on('error', gulpUtil.log))
		.pipe(autoprefixer({
			browsers: ['> 5%', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'] //兼容版本
		}))
		//.pipe(concat("demo.css")) 
		.pipe(gulpIf(sourcemap, sourcemaps.write("../sourcemap", {
			addComment: true,
			sourceRoot: "../css/"
		})))
		.pipe(gulp.dest(path.src.css))
})

/* 压缩css */
gulp.task("min-css", function() {
	return gulp.src(path.css)
		.pipe(autoprefixer({
			browsers: ['> 5%', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4']
		}))
		.pipe(cleanCSS({
			advanced: false, //类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
			compatibility: 'ie7', //保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
			keepBreaks: false //类型：Boolean 默认：false [是否保留换行]}))
		}))
		.pipe(gulpIf(version, rev()))
		.pipe(rename({
			suffix: ".min"
		}))
		.pipe(gulp.dest(path.dist.css))
		.pipe(gulpIf(version, rev.manifest()))
		.pipe(gulp.dest(path.src.cssVer));
});

/* 背景图合成雪碧图 */
gulp.task("spriter", function() {
	return gulp.src(path.css)
		.pipe(spriter({
			imagepath: path.catalog.img + "slice", //sprite背景图源文件夹
			spritedest: path.catalog.img, //雪碧图输出目录
			spritepath: "../img/", //css替换后的背景路径
			padding: 2, //图片间间距
			useimageset: false, //是否使用 image-set 作为2x图片实现
			newsprite: false,
			spritestamp: true //是否给雪碧图追加时间戳
		}))
		//.pipe(spriter({
		//'spriteSheet': path.catalog.img + 'sprite' + timestamp + '.png', //生成的spriter的位置
		//'pathToSpriteSheetFromCSS': '/resources/img/sprite' + timestamp + '.png'
		//}))
		.pipe(gulp.dest("./"));
})

/* 清除css文件版本信息(json) */
gulp.task("clean-cssVer", function() {
	return gulp.src(path.src.cssVer, {
			read: false
		})
		.pipe(clean());
});

/* js操作 */
/* 压缩js */
gulp.task("min-js", function() {
	return gulp.src(path.js)
		.pipe(plumber())
		.pipe(uglify().on('error', gulpUtil.log))
		.pipe(gulpIf(sourcemap, sourcemaps.init()))
		.pipe(gulpIf(version, rev()))
		.pipe(rename({
			suffix: ".min"
		}))
		.pipe(gulpIf(sourcemap, sourcemaps.write("../sourcemap", {
			addComment: true,
			sourceRoot: "../../../resouces/js/"
		})))
		//.pipe(gulp.dest(path.dist.js))
		.pipe(gulp.dest(path.dist.js))
		.pipe(gulpIf(version, rev.manifest()))
		.pipe(gulp.dest(path.src.jsVer));
});

/* 清除js文件版本信息(json) */
gulp.task("clean-jsVer", function() {
	return gulp.src(path.src.jsVer, {
			read: false
		})
		.pipe(clean());
});

gulp.task("rename-js", function() {
	return gulp.src(path.js)
		.pipe(rename({
			suffix: "-1.0"
		}))
		.pipe(gulp.dest(path.dist.js))
});

/* 图片操作 */
/* 常规图片压缩 */
gulp.task('min-img', function() {
	return gulp.src(path.img)
		//.pipe(imagemin())
		.pipe(imagemin({
			optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
			progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
			interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
			multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
		}))
		.pipe(gulpIf(version, rev()))
		.pipe(gulp.dest(path.dist.img))
		.pipe(gulpIf(version, rev.manifest()))
		.pipe(gulp.dest(path.src.imgVer));
});

/* 清除js文件版本信息(json) */
gulp.task("clean-imgVer", function() {
	return gulp.src(path.src.imgVer, {
			read: false
		})
		.pipe(clean());
});

/* jade模板操作 */
/* jade文件编译为html */
gulp.task("jade-html", function() {
	return gulp.src(path.jade)
		//.pipe(gulpData(function(file) {
			//return require("./" + path.src.data + gulpPath.basename(file.path).replace(".jade", '.json'));
		//}).on('error', gulpUtil.log))
		.pipe(jade({
			pretty: true
		}))
		.pipe(gulp.dest(path.src.jadeView));
})

/* jade文件编译为js */
gulp.task("jade-js", function() {
	return gulp.src(path.jade)
		.pipe(changed(path.src.jadeJs))
		.pipe(jade({
			client: true,
			pretty: true
		}).on('error', gulpUtil.log))
		.pipe(gulp.dest(path.src.jadeJs));
});

/* 生产发布 */
/* 更新页面静态资源的版本信息 */
gulp.task("update-view", function() {
	return gulp.src([path.src.ver + "**/*.json", path.src.view + "**/*.html"])
		.pipe(revCollector({
			replaceReved: true
		}))
		.pipe(gulp.dest(path.dist.view));
});

/* 更新css中图片资源的版本信息 */
gulp.task("update-css", function() {
	return gulp.src([path.src.ver + "**/*.json", path.dist.css + "**/*.css"])
		.pipe(revCollector({
			replaceReved: true
		}))
		.pipe(gulp.dest(path.dist.css));
});

/* 清除生产目录内容 */
gulp.task("clean-dist", function() {
	return gulp.src(path.dist.all, {
			read: false
		})
		.pipe(clean());
});

/* 复制font文件 */
gulp.task("copy-font", function() {
	return gulp.src(path.src.font)
		.pipe(gulp.dest(path.dist.font));
});

/* 复制data文件 */
gulp.task("copy-data", function() {
	return gulp.src(path.src.data + "**/*")
		.pipe(gulp.dest(path.dist.data));
});

/* 复制dep文件 */
gulp.task("copy-dep", function() {
	return gulp.src(path.src.dep)
		.pipe(gulp.dest(path.dist.dep));
});

/* 实时刷新 */
gulp.task('browser-sync', function() {
	files: "**",
	//更改默认端口
	browserSync.init({
		server: {
			baseDir: project,
			directory: true,
			index: ""
		},
		port: 8090, //端口号
		ui: {
			port: 8091
		}
	});
});

/* css修改后的操作 */
gulp.task("css", function(fn) {
	if (build) {
		runSequence("clean-cssVer", "spriter", "min-css", "update-view", fn);
	}
});

/* sass修改后的操作 */
gulp.task("sass", function(fn) {
	if (build) {
		runSequence("compile-sass", "css", fn);
	} else {
		runSequence("compile-sass", fn);
	}
});

/* js修改后的操作 */
gulp.task("js", function(fn) {
	if (build) {
		runSequence("clean-jsVer", "min-js", "update-view", fn);
	}
});

/* image修改后的操作 */
gulp.task("img", function(fn) {
	runSequence("clean-imgVer", "min-img", "update-view", "update-css", fn);
});

/* jade修改后的操作 */
gulp.task("jade", function(fn) {
	//runSequence("jade-html", "jade-js", fn);
	runSequence("jade-html", fn);
});

/* 生产环境发布相关操作 */
gulp.task("build", function() {
	version = build = true;
	runSequence("clean-dist", ["copy-data", "copy-font", "copy-dep"], "css", "js", "img");
});

//创建项目目录结构
gulp.task("init", function() {
	var oSrc = path.catalog,
		aKeys = Object.keys(oSrc),
		nResult = [];
	for (var i = 0; i < aKeys.length; i++) {
		nResult.push(createDir(oSrc[aKeys[i]]));
	}
	Promise.all(nResult)
		.then(function(value) {
			console.log(gulpUtil.colors.blue("init success!"));
			console.log(value);
		})
		.catch(function(error) {
			console.log(gulpUtil.colors.red(error));
		});
});

function createDir(path) {
	return new Promise(function(resolve, reject) {
		mkdirp(path, function(err) {
			if (err) {
				reject(err);
			} else {
				gulp.src(path)
					.pipe(gulpAdd(".gitignore", "# Ignore everything in this directory * # Except this file !.gitignore"))
					.pipe(gulp.dest(path));
				resolve(path);
			}
		});
	});
}

/* default task */
gulp.task('default', ["browser-sync"], function() {
	gulp.watch(path.view).on('change', reload);
	gulp.watch(path.css, ["css"]).on('change', reload);
	gulp.watch(path.sass, ["sass"]).on('change', reload);
	gulp.watch(path.js, ["js"]).on('change', reload);
	gulp.watch(path.jade, ["jade"]).on('change', reload);
});